package com.workable.assignment.exceptions;

import javax.ws.rs.core.Response;

import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;

import com.workable.assignment.Constants;
import com.workable.assignment.annotations.MovieRamaExceptionHandler;
import com.workable.assignment.services.ws.factories.MovieRamaResponseFactory;
import com.workable.assignment.utilities.StringUtil;

/**
 * The class MovieRamaExceiptionHandlerInterception implements exception handling mechanism
 */
@Aspect
@Component
public class MovieRamaExceiptionHandlerInterceptor {

    private static final Logger LOG = (Logger) LoggerFactory.getLogger(MovieRamaExceiptionHandlerInterceptor.class);

    @Around("@annotation(movieRamaExceptionHandler)")
    public Object intercept(ProceedingJoinPoint pjp, MovieRamaExceptionHandler movieRamaExceptionHandler) {

        String statusCode;
        String description;
        Response successReply = null;
        try {
            successReply = (Response) pjp.proceed();
            return successReply;
        } catch (Throwable ex) {
            LOG.error("{} : {}", pjp.getSignature().toShortString(), ex.getMessage(), ex);
            statusCode = Constants.STATUS_ERROR;
            description = Constants.STATUS_ERROR_MESSAGE;
        } finally {
            if (LOG.isDebugEnabled()) {
                LOG.debug("{}: {}", pjp.getSignature().toShortString(), StringUtil.toString(successReply));
            }
        }

        return MovieRamaResponseFactory.createResponse(null, statusCode, description);
    }
}